<?php

namespace App\Listeners\CommentCreated;

use App\Events\CommentCreated;
use App\Models\Comment;
use App\Notifications\CommentReplied;
use App\Notifications\TopicReplied;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SendNotification
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  CommentCreated  $event
     * @return void
     */
    public function handle(CommentCreated $event)
    {
        $comment = $event->comment;
        $commentUser = $comment->user;
        $topic = $comment->topic;

        $log = __METHOD__;
        //若是回复评论。
        if ($comment->pid) {
            $parentComment = $comment->parentComment;
            //先给父评论发
            if ($parentComment->uid != $comment->uid) {
                $parentCommentUser = $parentComment->user;
                $parentCommentUser->notify(new CommentReplied($parentComment, $commentUser, $comment));
                $log .= ", to parent comment user: " . $parentCommentUser->id;
            }
            //再给帖子作者发
            if ($topic->uid != $comment->uid && $topic->uid != $parentComment->uid) {
                $topicUser = $topic->user;
                $topicUser->notify(new TopicReplied($topic, $commentUser, $comment));
                $log .= ", then to topic user: " . $topicUser->id;
            }
        } else {
            //没有回复评论，直接回复帖子
            if ($topic->uid != $comment->uid) {
                $topicUser = $topic->user;
                $topicUser->notify(new TopicReplied($topic, $commentUser, $comment));
                $log .= ", direct to topic user: " . $topicUser->id;
            }
        }

        logger($log);
    }
}
